//
//  TLAudioPlayer.m
//  TLChat
//
//  Created by 李伯坤 on 16/7/12.
//  Copyright © 2016年 李伯坤. All rights reserved.
//

#import "WBTLAudioPlayer.h"
#import <AVFoundation/AVFoundation.h>

@interface WBTLAudioPlayer() <AVAudioPlayerDelegate>

@property (nonatomic, assign) BOOL isPlaying;

@property (nonatomic, strong) void (^ completeBlock)(BOOL finished);

@property (nonatomic, strong) AVAudioPlayer *player;

@end

@implementation WBTLAudioPlayer

+ (WBTLAudioPlayer *)sharedAudioPlayer
{
    static WBTLAudioPlayer *audioPlayer;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        audioPlayer = [[WBTLAudioPlayer alloc] init];
        ///监听播放器的播放状态
        [audioPlayer addObserver:audioPlayer forKeyPath:@"isPlaying" options: NSKeyValueObservingOptionNew context:NULL];
    });
    return audioPlayer;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    //拿到新值/旧值,进行操作
    if (self.player.isPlaying) {
        if ([[UIDevice currentDevice] proximityState] == YES){
            ///听筒模式
            NSLog(@"恢复听筒模式");
            ///恢复听筒模式
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        }
        else{
            ///免提模式
            NSLog(@"恢复外放模式");
            ///恢复外放模式
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        }
        
    }
    else{
        NSLog(@"恢复外放模式并关闭红外感应");
        ///恢复外放模式
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        ///关闭红外感应
        [[UIDevice currentDevice]setProximityMonitoringEnabled:NO];
    }
    
}
- (void)playAudioAtPath:(NSString *)path complete:(void (^)(BOOL finished))complete{
    NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path]];
    [self playAudioWith:data complete:complete];
}
- (void)playAudioWith:(NSData *)data complete:(void (^)(BOOL finished))complete
{

    if (self.player && self.player.isPlaying) {
        [self stopPlayingAudio];
    }
    self.completeBlock = complete;
    NSError *error;
    self.player = [[AVAudioPlayer alloc] initWithData:data error:&error];
    [self.player setDelegate:self];
    if (error) {
        if (complete) {
            complete(NO);
        }
        return;
    }
    ///启动红外感应
    [[UIDevice currentDevice]setProximityMonitoringEnabled:YES];
    [self.player play];

}

- (void)stopPlayingAudio
{

    [[NSNotificationCenter defaultCenter]postNotificationName:NCChatViewCellAudioPlayStopNotifi object:nil];
    [self.player stop];
    self.isPlaying = NO;
    if (self.completeBlock) {
        self.completeBlock(NO);
    }
}

- (BOOL)isPlaying
{
    if (self.player) {
        return self.player.isPlaying;
    }
    return NO;
}

#pragma mark - # Delegate
//MARK: AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    self.isPlaying = NO;
    if (self.completeBlock) {
        self.completeBlock(YES);
        self.completeBlock = nil;
    }
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
    self.isPlaying = NO;
    if (self.completeBlock) {
        self.completeBlock(NO);
        self.completeBlock = nil;
    }
}

@end
